import urllib
import xbmcplugin
import xbmcgui
import xbmc
import simplejson as json
import sys
import os

# Insert your GiantBomb API key
apiKey = "0a204c5b48872c635a858970050ec807c381b13e"

mainUrl = "http://api.giantbomb.com/videos/?api_key=%(key)s&field_list=%(flist)s&format=json&limit=%(lim)s&offset=%(offset)s&sort=publish_date"
templateUrl = "http://media.giantbomb.com/video/%(url)s_"
endHQ = "1500.flv"
endLQ = "700.flv"
field_list = "name,url,image,deck,publish_date"
videos_per_req = 100
fileName = os.getcwd() + '/video.dat'
fileCheckString = "THEFILEISCOMPLETE1234567890"

# object_hooks, used to extraxt data from the json string
def as_numVideos(dct):
    return dct['number_of_total_results']

def as_numResults(dct):
    return dct['number_of_page_results']

def as_url(dct):
    return dct['url']

def as_name(dct):
    return dct['name']
    
def as_deck(dct):
    return dct['deck']
    
def as_imageThumb(dct):
    return dct['super_url']

def as_date(dct):
    return dct['publish_date']

# update the video list    
def updateVideos():

    # Check file and read video number
    FILE = open(fileName, 'r+')
    sNumba = FILE.readline()
    fileContent = FILE.readlines()
    FILE.close()
    
    try:
        numba = int(sNumba)
    except:
        numba = -1
    
    # Get number of videos
    f = urllib.urlopen( mainUrl%{'key':apiKey, 'flist':"", 'lim':"1", 'offset': "0"} )
    s = f.read()
    numVideos = json.loads(s, object_hook=as_numVideos)
    
    # Check if the file is complete
    fileOk = str(fileContent).find(fileCheckString)
    
    # Check if update is needed
    if numVideos == numba and fileOk != -1:
        return
    
    # Create new data file
    FILE = open(fileName, 'w')
    FILE.write( str(numVideos) + "\n" )
    
    # Write old video data
    iCount = 0
    if fileOk != -1:
        lastDate = fileContent[len(fileContent)-3]    
        done = False
        while done == False:
            tmpDate = fileContent[len(fileContent)-(3+iCount*5)]
            if lastDate != tmpDate:
                done = True
            else:
                iCount += 1
        FILE.writelines( fileContent[0:len(fileContent)-(1+iCount*5)] )
    
    pDialog = xbmcgui.DialogProgress()
    pDialog.create('GiantBomb Videos', 'Data created and powered by Giant Bomb')
    pDialog.update(1, 'Initializing script...')
    
    offset = numba - iCount
    while (offset < numVideos):

        # Get the data    
        videoList = mainUrl%{'key':apiKey, 'flist':str(field_list), 'lim':str(videos_per_req), 'offset': str(offset)}
        f = urllib.urlopen(videoList)
        s = f.read()
        
        # Extract results
        start = s.find('[') +1
        end = s.find('}],') +1
        sResults = s[start:end]
        s2 = s[0:start-1] + ' "1"' + s[end+1:len(s)]
        numRes = json.loads(s2, object_hook=as_numResults)
        
        for i in range(0, numRes):
        
            # Extra result
            posStart = 0
            if i == numRes-1:
                posEnd = len(sResults)
            else:
                posEnd = sResults.find('}, {') +1;
            tempRes = sResults[posStart:posEnd]
            
            # Extract images
            posImageStart = tempRes.find("image") +8
            posImageEnd = tempRes.find('}') +1;
            tempImages = tempRes[posImageStart:posImageEnd]
            finImage = json.loads(tempImages, object_hook=as_imageThumb)
            tempRes = tempRes[0:posImageStart -9] + tempRes[posImageEnd+1:len(sResults)]
            
            # Extract name
            finName = json.loads(tempRes, object_hook=as_name)
            
            # Extract date
            tempDate = json.loads(tempRes, object_hook=as_date)
            finDate = tempDate[8:10] + '-' + tempDate[5:7] + '-' + tempDate[0:4]
            
            # Extract deck
            finDeck = json.loads(tempRes, object_hook=as_deck)
            finDeck = finDeck.replace("\n","") # Remove any newlines
            finDeck = finDeck.replace("\r","") # Remove any newlines
            
            # Extract url
            tempUrl = json.loads(tempRes, object_hook=as_url)
            tempUrl = tempUrl[0:len(tempUrl)-4]
            finishedUrl = templateUrl%{'url':tempUrl}
            finUrl = str(finishedUrl)
            
            # Add to file
            FILE.write( finName.encode("utf-8") + "\n" + finUrl.encode("utf-8") + "\n" + finImage.encode("utf-8") + "\n" + finDate.encode("utf-8") + "\n" + finDeck.encode("utf-8") + "\n")
                
            # Remove results from the rest
            sResults = sResults[posEnd+2:len(sResults)]
            
            pct = float(offset+i-(numba - iCount)) / float(numVideos-(numba - iCount)) * float(100)
            iPct = int(pct+0.5)
            pDialog.update(iPct, 'Data created and powered by Giant Bomb', 'Importing video data from GiantBomb.com')
            
        # Change offset
        offset = offset + videos_per_req

    FILE.write(str(fileCheckString) + "\n")
    pDialog.close()
    FILE.close()
    
# displays videos, based on the filter    
def addVideosFile(filt, optName=""):
    
    # Get video quality setting
    cQuality = xbmcplugin.getSetting('vquality')
    if (cQuality == '1') :
        endString = endHQ
    else:
        endString = endLQ

    # Write to the data file
    FILE = open(fileName, 'r')

    sNumba = FILE.readline()
    numba = int(sNumba)
    
    numVideosAdded = 0

    for i in range(0,numba+1):
        name = FILE.readline()
        name = optName + name[0:len(name)-1]
        
        found = 0
        if (filt == "") :
            found = 1
        else:
            for x in range(0, len(filt)):
                if( name.find(filt[x]) != -1):
                    found = 1
                    
        url = FILE.readline()
        url = url[0:len(url)-1] + endString
        image = FILE.readline()
        image = image[0:len(image)-1]
        date = FILE.readline()
        date = date[0:len(date)-1]
        deck = FILE.readline()
        deck = deck[0:len(deck)-1]
            
        if ( found == 1 ):
            numVideosAdded = numVideosAdded + 1
            numbaTmp = float(numVideosAdded) / float( float(i+1) / float(numba) )
            addLink(name, url, image, date, deck, numbaTmp)
        
    FILE.close()

def CATEGORIES():
    addDir( 'All' )
    addDir( 'Endurance Run' )
    addDir( 'Game Of The Year' )
    addDir( 'Giant Bomb Mailbag' )
    addDir( 'How To Build A Bomb' )
    addDir( 'I Love Mondays' )
    addDir( 'QOTW' )
    addDir( 'Quick looks' )
    addDir( 'Reviews' )
    addDir( 'Star Trek Online' )
    addDir( 'TANG' )
    addDir( 'The Matrix Online' )
    addDir( 'Trailers' )

def VIDEOLINKS(name):
    if name == 'All':
        addVideosFile([''])
    
    elif name == 'Endurance Run':
        addVideosFile(['Endurance Run:'])
        
    elif name == 'The Matrix Online':
        addVideosFile(['The Matrix Online: Not Like This'])
    
    elif name == 'Quick looks':
        addDir( 'Quick look of the Year: 2009' )
        addVideosFile(['Quick Look'])
            
    elif name == 'Reviews':
        addVideosFile(['Review'])
            
    elif name == 'Trailers':
        addVideosFile(['Trailer'])
            
    elif name == 'TANG':
        addVideosFile(['TANG:', 'No Game:', 'No Game -'])
        
    elif name == 'Game Of The Year':
        addVideosFile(['GOTY', 'Game of the Year', 'Top 10 Games of'])
        
    elif name == 'QOTW':
        addVideosFile(['QOTW'])

    elif name == 'I Love Mondays':
        addVideosFile(['I Love Mondays'])

    elif name == 'Star Trek Online':
        addVideosFile(['Set Phasers to Fun'])
        
    elif name == 'How To Build A Bomb':
        addVideosFile(['How To Build A Bomb'])
        
    elif name == 'Quick look of the Year: 2009':
        addVideosFile(['Jackie Chan in Fists of Fire'], "10 - ")
        addVideosFile(['Quick Look: Tony Hawk: RIDE'], "09 - ")
        addVideosFile(['Incredible Crisis'], "08 - ")
        addVideosFile(['Story Hour: Adventures'], "07 - ")
        addVideosFile(['Quick Look: Darkest of Days'],"06 - ")
        addVideosFile(['Quick Look: Rogue Warrior'],"05 - ")
        addVideosFile(['Quick Look: Dragonball: Evolution'],"04 - ")
        addVideosFile(['Quick Look: Harry Potter'], "03 - ")
        addVideosFile(['Quick Look: Noby Noby Boy'],"02 - ")
        addVideosFile(['Quick Look: New Super Mario Bros. Wii'],"01 - ")
        
    elif name == 'Giant Bomb Mailbag':
        addVideosFile(['Mailbag'])
                        
def get_params():
    param=[]
    paramstring=sys.argv[2]
    if len(paramstring)>=2:
            params=sys.argv[2]
            cleanedparams=params.replace('?','')
            if (params[len(params)-1]=='/'):
                    params=params[0:len(params)-2]
            pairsofparams=cleanedparams.split('&')
            param={}
            for i in range(len(pairsofparams)):
                    splitparams={}
                    splitparams=pairsofparams[i].split('=')
                    if (len(splitparams))==2:
                            param[splitparams[0]]=splitparams[1]
    return param

def addLink(name,url,iconimage, date, deck, totalItems):
    ok=True
    liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    liz.setInfo( type="Video", infoLabels={ "Title": name , "Date": date, "Plot": deck} )
    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz, totalItems=int(totalItems))
    return ok

def addDir(name):
    url=''
    u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(2)+"&name="+urllib.quote_plus(name)
    ok=True
    liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage='')
    liz.setInfo( type="Video", infoLabels={ "Title": name } )
    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
    return ok

# Start 
updateVideos()   
params=get_params()
name=None
mode=None

try:
    name=urllib.unquote_plus(params["name"])
except:
    pass

try:
    mode=int(params["mode"])
except:
    pass

if mode==None:
    CATEGORIES()
        
elif mode==2:
    VIDEOLINKS(name)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)

xbmcplugin.endOfDirectory(int(sys.argv[1]))